<?php

function pical_search( $queryarray , $andor , $limit , $offset , $userid )
{
	global $xoopsDB , $xoopsUser ;

	if( is_object( $xoopsUser ) ) {
		if( $xoopsUser->isadmin() ) {
			// Administrator
			$whr_class = '1' ;
		} else {
			// Normal User
			$groups =& $xoopsUser->groups() ;
			$ids = '' ;
			foreach( $groups as $id ) {
				$ids .= "$id," ;
			}
			$ids = substr( $ids , 0 , -1 ) ;
			if( intval( $ids ) == 0 ) $group_section = '' ;
			else $group_section = "OR groupid IN ($ids)" ;
			$whr_class = "(class='PUBLIC' OR uid='".$xoopsUser->uid()."' $group_section)" ;
		}
	} else {
		// Guest can only search PUBLIC records
		$whr_class = "class='PUBLIC'" ;
	}

	$sql = "SELECT id,uid,summary,UNIX_TIMESTAMP(dtstamp), start, end, allday FROM ".$xoopsDB->prefix("pical_event")." WHERE admission>0 AND (rrule_pid=0 OR rrule_pid=id) AND $whr_class";
	if ( $userid != 0 ) {
		$sql .= " AND uid=".$userid." ";
	}

	// because count() returns 1 even if a supplied variable
	// is not an array, we must check if $querryarray is really an array
	if ( is_array($queryarray) && $count = count($queryarray) ) {
		$sql .= " AND ((summary LIKE '%$queryarray[0]%' OR location LIKE '%$queryarray[0]%' OR contact LIKE '%$queryarray[0]%' OR description LIKE '%$queryarray[0]%')";
		for($i=1;$i<$count;$i++){
			$sql .= " $andor ";
			$sql .= "(summary LIKE '%$queryarray[$i]%' OR location LIKE '%$queryarray[$i]%' OR contact LIKE '%$queryarray[$i]%' OR description LIKE '%$queryarray[$i]%')";
		}
		$sql .= ") ";
	}

	$sql .= "ORDER BY dtstamp DESC";
	$result = $xoopsDB->query( $sql , $limit , $offset ) ;
	$ret = array() ;
	$i = 0 ;
	while( list( $id , $uid , $summary , $dtstamp , $start , $end , $allday ) = $xoopsDB->fetchRow( $result ) ) {

		if( $allday ) $end -= 300 ;

		$start_str = formatTimestamp( $start , 's' ) ;
		$end_str = formatTimestamp( $end , 's' ) ;
		$ymd = ( $start_str == $end_str ) ? $start_str : "$start_str - $end_str" ;
		$ret[$i]['image'] = "images/pical.gif" ;
		$ret[$i]['link'] = "index.php?action=View&amp;event_id=$id" ;
		$ret[$i]['title'] = "[$ymd] $summary" ;
		$ret[$i]['time'] = $dtstamp ;
		$ret[$i]['uid'] = $uid ;
		$i ++ ;
	}
	return $ret ;
}
?>
